// utils/stockApi.js - 股票数据API服务

/**
 * 股票数据API工具类
 */
class StockAPI {
  constructor() {
    // 腾讯财经API基础URL
    this.tencentBaseUrl = 'https://qt.gtimg.cn/q=';
    // 新浪财经API基础URL  
    this.sinaBaseUrl = 'https://hq.sinajs.cn/list=';
  }

  /**
   * 格式化股票代码
   * @param {string} code - 原始股票代码
   * @returns {string} - 格式化后的代码
   */
  formatStockCode(code) {
    // 去除空格和特殊字符
    code = code.replace(/\s+/g, '').toUpperCase();

    // 如果已经有前缀，直接返回
    if (code.startsWith('SH') || code.startsWith('SZ') || code.startsWith('US')) {
      return code.toLowerCase();
    }

    // 根据代码判断市场
    if (code.startsWith('6')) {
      return 'sh' + code; // 上海股市
    } else if (code.startsWith('0') || code.startsWith('3')) {
      return 'sz' + code; // 深圳股市
    } else {
      return 'sh' + code; // 默认上海
    }
  }

  /**
   * 解析腾讯财经返回的数据
   * @param {string} data - 原始数据字符串
   * @returns {object} - 解析后的股票数据
   */
  parseTencentData(data) {
    try {
      // 提取引号内的数据
      const match = data.match(/"([^"]+)"/);
      if (!match) return null;

      const fields = match[1].split('~');

      return {
        code: fields[2] || '',
        name: fields[1] || '',
        currentPrice: parseFloat(fields[3]) || 0,
        yesterdayClose: parseFloat(fields[4]) || 0,
        todayOpen: parseFloat(fields[5]) || 0,
        volume: parseInt(fields[6]) || 0,
        change: parseFloat(fields[31]) || 0,
        changePercent: parseFloat(fields[32]) || 0,
        high: parseFloat(fields[33]) || 0,
        low: parseFloat(fields[34]) || 0,
        updateTime: fields[30] || '',
        // 买卖盘数据
        buy1: parseFloat(fields[9]) || 0,
        buy1Volume: parseInt(fields[10]) || 0,
        sell1: parseFloat(fields[19]) || 0,
        sell1Volume: parseInt(fields[20]) || 0,
        // 市值数据
        marketValue: parseFloat(fields[45]) || 0,
        pe: parseFloat(fields[39]) || 0,
        pb: parseFloat(fields[46]) || 0
      };
    } catch (error) {
      console.error('解析腾讯数据失败:', error);
      return null;
    }
  }

  /**
   * 获取单只股票实时数据
   * @param {string} code - 股票代码
   * @returns {Promise<object>} - 股票数据
   */
  async getStockData(code) {
    try {
      const formattedCode = this.formatStockCode(code);
      const url = this.tencentBaseUrl + formattedCode;

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: url,
          method: 'GET',
          success: resolve,
          fail: reject
        });
      });

      if (response.statusCode === 200) {
        const stockData = this.parseTencentData(response.data);
        return {
          success: true,
          data: stockData
        };
      } else {
        throw new Error(`请求失败: ${response.statusCode}`);
      }
    } catch (error) {
      console.error('获取股票数据失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 批量获取股票数据
   * @param {Array<string>} codes - 股票代码数组
   * @returns {Promise<Array>} - 股票数据数组
   */
  async getBatchStockData(codes) {
    try {
      const formattedCodes = codes.map(code => this.formatStockCode(code));
      const url = this.tencentBaseUrl + formattedCodes.join(',');

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: url,
          method: 'GET',
          success: resolve,
          fail: reject
        });
      });

      if (response.statusCode === 200) {
        const lines = response.data.split('\n').filter(line => line.trim());
        const stockList = lines.map(line => this.parseTencentData(line)).filter(data => data);

        return {
          success: true,
          data: stockList
        };
      } else {
        throw new Error(`请求失败: ${response.statusCode}`);
      }
    } catch (error) {
      console.error('批量获取股票数据失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 搜索股票
   * @param {string} keyword - 搜索关键词
   * @returns {Promise<Array>} - 搜索结果
   */
  async searchStock(keyword) {
    // 扩展的股票数据库用于搜索
    const stockDatabase = [
      { code: '000001', name: '平安银行', market: 'sz' },
      { code: '000002', name: '万科A', market: 'sz' },
      { code: '000858', name: '五粮液', market: 'sz' },
      { code: '002415', name: '海康威视', market: 'sz' },
      { code: '002594', name: '比亚迪', market: 'sz' },
      { code: '300059', name: '东方财富', market: 'sz' },
      { code: '300750', name: '宁德时代', market: 'sz' },
      { code: '600036', name: '招商银行', market: 'sh' },
      { code: '600276', name: '恒瑞医药', market: 'sh' },
      { code: '600519', name: '贵州茅台', market: 'sh' },
      { code: '600887', name: '伊利股份', market: 'sh' },
      { code: '601318', name: '中国平安', market: 'sh' },
      { code: '601398', name: '工商银行', market: 'sh' },
      { code: '601888', name: '中国中免', market: 'sh' },
      { code: '603259', name: '药明康德', market: 'sh' }
    ];

    const results = stockDatabase.filter(stock =>
      stock.name.includes(keyword) ||
      stock.code.includes(keyword)
    );

    return {
      success: true,
      data: results
    };
  }

  /**
   * 获取热门股票列表
   * @returns {Promise<Array>} - 热门股票数据
   */
  async getHotStocks() {
    const hotStockCodes = [
      '000001', // 平安银行
      '000002', // 万科A  
      '600519', // 贵州茅台
      '600036', // 招商银行
      '601318', // 中国平安
      '000858', // 五粮液
      '002415', // 海康威视
      '600276'  // 恒瑞医药
    ];

    return await this.getBatchStockData(hotStockCodes);
  }

  /**
   * 获取涨幅榜
   * @returns {Promise<Array>} - 涨幅榜数据
   */
  async getRiseRanking() {
    const codes = ['002594', '300750', '600519', '000858', '601318', '600036', '002415', '600276'];
    const result = await this.getBatchStockData(codes);

    if (result.success) {
      // 按涨幅排序
      const sortedData = result.data.sort((a, b) => b.changePercent - a.changePercent);
      return {
        success: true,
        data: sortedData
      };
    }
    return result;
  }

  /**
   * 获取跌幅榜
   * @returns {Promise<Array>} - 跌幅榜数据
   */
  async getFallRanking() {
    const codes = ['000001', '000002', '600887', '601398', '601888', '603259', '300059', '600276'];
    const result = await this.getBatchStockData(codes);

    if (result.success) {
      // 按跌幅排序
      const sortedData = result.data.sort((a, b) => a.changePercent - b.changePercent);
      return {
        success: true,
        data: sortedData
      };
    }
    return result;
  }

  /**
   * 获取成交额榜
   * @returns {Promise<Array>} - 成交额榜数据
   */
  async getVolumeRanking() {
    const codes = ['600519', '000858', '002594', '300750', '601318', '600036', '002415', '000001'];
    const result = await this.getBatchStockData(codes);

    if (result.success) {
      // 按成交量排序
      const sortedData = result.data.sort((a, b) => b.volume - a.volume);
      return {
        success: true,
        data: sortedData
      };
    }
    return result;
  }

  /**
   * 获取换手率榜
   * @returns {Promise<Array>} - 换手率榜数据
   */
  async getTurnoverRanking() {
    const codes = ['300059', '002415', '300750', '002594', '600276', '603259', '000002', '600887'];
    const result = await this.getBatchStockData(codes);

    if (result.success) {
      // 模拟换手率数据并排序
      const dataWithTurnover = result.data.map(item => ({
        ...item,
        turnoverRate: (Math.random() * 10).toFixed(2) // 模拟换手率
      }));
      const sortedData = dataWithTurnover.sort((a, b) => b.turnoverRate - a.turnoverRate);
      return {
        success: true,
        data: sortedData
      };
    }
    return result;
  }

  /**
   * 获取龙虎榜数据
   * @returns {Promise<Array>} - 龙虎榜数据
   */
  async getDragonTigerList() {
    const dragonTigerData = [
      {
        code: '002594',
        name: '比亚迪',
        changePercent: 8.56,
        currentPrice: 245.67,
        reason: '日涨幅偏离值达7%',
        buyAmount: 12.5,
        sellAmount: 8.3,
        netAmount: 4.2
      },
      {
        code: '300750',
        name: '宁德时代',
        changePercent: 6.78,
        currentPrice: 198.45,
        reason: '日振幅值达15%',
        buyAmount: 18.7,
        sellAmount: 15.2,
        netAmount: 3.5
      },
      {
        code: '002415',
        name: '海康威视',
        changePercent: -5.23,
        currentPrice: 32.18,
        reason: '日跌幅偏离值达7%',
        buyAmount: 6.8,
        sellAmount: 11.2,
        netAmount: -4.4
      },
      {
        code: '300059',
        name: '东方财富',
        changePercent: 4.12,
        currentPrice: 15.67,
        reason: '连续三个交易日内涨幅偏离值累计达20%',
        buyAmount: 9.3,
        sellAmount: 7.1,
        netAmount: 2.2
      }
    ];

    return {
      success: true,
      data: dragonTigerData
    };
  }
}

// 创建全局实例
const stockAPI = new StockAPI();

module.exports = stockAPI;
